<template>
    <el-card style="margin: 16px">
        <el-form v-show="showSearch" :inline="true" ref="queryForm" :model="formInline" class="demo-form-inline"
                 :label-width="100">
            <el-form-item label="任务名称">
                <el-input v-model="formInline.syncTaskName" placeholder="请输入任务名称" clearable/>
            </el-form-item>
            <el-form-item label="源端数据源">
                <el-select v-model="formInline.readerDatasourceId" clearable>
                    <el-option v-for="(opt, index) in sourceList"  :key="index" :value="opt.datasourceId" :label="opt.datasourceName" />
                </el-select>
            </el-form-item>
            <el-form-item label="目的端数据源">
                <el-select v-model="formInline.writerDatasourceId" clearable>
                    <el-option v-for="(opt, index) in sourceList" :key="index" :value="opt.datasourceId" :label="opt.datasourceName" />
                </el-select>

            </el-form-item>
            <el-form-item label="类型">
<!--                <el-input v-model="formInline.syncTaskType" placeholder="请输入类型" clearable/>-->
                <el-select v-model="formInline.syncTaskType" clearable>
                    <el-option v-for="item in syncTaskTypeList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
                </el-select>

            </el-form-item>
            <el-form-item>
                <search-button @click="onSubmit"/>
                <reset-button @click="onReset"/>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <add-button @click="handleAction({},'add')"/>
            <delete-button :disabled="!selectedRows.length" @click="handleDelAction"/>
            <right-toolbar v-model:showSearch="showSearch" @query-table="getList"/>
        </el-row>
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="syncTaskName" label="任务名称" width="280"/>
            <el-table-column prop="syncTaskType" label="类型" width="100">
                <template #default="scope">
                     {{ selectDictLabel(syncTaskTypeList, scope.row.syncTaskType) }}
                </template>
            </el-table-column>
            <el-table-column prop="readerDatasourceId" label="源端数据源">
                <template #default="scope">
                    {{handleDatasource( scope.row.readerDatasourceId)}}
<!--                    {{ selectDictLabel(sourceList, scope.row.readerDatasourceId) }}-->
                </template>
            </el-table-column>
            <el-table-column prop="writerDatasourceId" label="目的端数据源">
                <template #default="scope">
                    {{ handleDatasource(scope.row.writerDatasourceId) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" align="center" label="更新时间" width="180"/>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" type="primary" link @click="handleAction(scope.row,'view')">查看</el-button>
                    <el-button link type="primary" size="small" @click="handleAction(scope.row,'copy')">复制</el-button>
                    <el-button link type="primary" size="small" @click="handleAction(scope.row,'edit')">修改</el-button>
                    <el-button link type="danger" size="small" @click="handleDelAction(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="formInline.pageNum"
                    v-model:limit="formInline.pageSize" @pagination="getList"/>
        <CollectionDialog @confirm="confirm" v-if="formData.open" v-model="formData.open"
                          :formData="formData"
                          :sourceList="sourceList"
                          :scriptList="scriptList"
                          :dayWayList="dayWayList"
                          :syncTaskTypeList="syncTaskTypeList"
                          :title="formData.title"/>
    </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {resetFormPlus,selectDictLabel} from '@/utils/zmids'
import { search as datasourceList } from '@data/api/data/datasource'
import { search as datascriptList } from '@data/api/data/datascript'

import CollectionDialog from './components/collectionDialog.vue';
import {searchByEntity, selectById, deleteById} from '@data/api/data/datacollection/api'
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import { getDicts } from '@base/api/base/dict/data'

const queryForm = ref<FormInstance>() // 查询表单参数ref
const total = ref<number>(0) // 序列管理信息总数

const initialFormInline = {
  syncTaskName: '',
  readerDatasourceId: '',
  writerDatasourceId: '',
  syncTaskType: '',
  pageNum: 1,
  pageSize: 10,
};
const formInline = reactive({
  ...initialFormInline, // 使用初始值初始化
});

const formData = reactive({
    open: false,
    title: '',
    data: {},
});

const tableData = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const showSearch = ref(true);
const sourceList = ref<any[]>([]);
const dayWayList = ref<any[]>([]);
const syncTaskTypeList = ref<any[]>([]);
const scriptList = ref<any[]>([]);

const handleDatasource = (id: string) => {
    const item = sourceList.value.find((item) => item.datasourceId === id);
    if (item) {
        return item.datasourceName;
    } else {
        return '';
    }
}
const getList = () => {
    searchByEntity(formInline).then((res) => {
        if (res) {
            tableData.value = res.data.list;
            total.value = res.data.total;
        }
    });
};

const getSourceList = () => {
    datasourceList({
      }).then(response => {
            sourceList.value = response.data.list;
            // console.log(sourceList.value)
    });
};


const getDayWayList= () => {
    getDicts('data_sync_way').then((response) => {
        dayWayList.value = response.data
    })
};

const getSyncTaskTypeList = () => {
    getDicts('data_sync_task_type').then((response) => {
        syncTaskTypeList.value = response.data
    })
}

const getScriptList = () => {
  datascriptList({
      }).then(response => {
            scriptList.value = response.data.list;
            // console.log(scriptList.value)
    });
}

onMounted(() => {
    getList();
    getSourceList();
    getDayWayList();
    getSyncTaskTypeList();
    getScriptList();
})


const onSubmit = () => {
    getList();
};
const onReset = () => {
    Object.assign(formInline, initialFormInline); // 重置为初始值
    resetFormPlus(queryForm.value);
    getList();
};
const handleSelectionChange = (val: any) => {
    selectedRows.value = val;
};
const handleAction = (row: object, type: string) => {
    if (type === 'add') {
        formData.data ={};
        formData.title = '新增';
        formData.open = true;
    } else if (type === 'copy') {
        formData.title = '复制';
        selectById({syncTaskId:row.syncTaskId}).then(response => {
            if(response.data.dataSyncColumnDTOList?.length>0) {
                response.data.fColumnList = [];
                response.data.tColumnList = [];
                response.data.dataSyncColumnDTOList.forEach((item: any) => {
                    response.data.fColumnList.push({
                      name: item.srcColumnName,
                      isChecked: true
                    })
                    response.data.tColumnList.push({
                      name: item.targetColumnName,
                      isChecked: true
                    })
                })
            }
            formData.data = response.data;
            formData.data.syncTaskId = undefined;
            formData.open = true;
        });
    } else if (type === 'edit') {
        formData.title = '修改';
        selectById({syncTaskId:row.syncTaskId}).then(response => {
            if(response.data.dataSyncColumnDTOList?.length>0) {
                response.data.fColumnList = [];
                response.data.tColumnList = [];
                response.data.dataSyncColumnDTOList.forEach((item: any) => {
                    response.data.fColumnList.push({
                        name: item.srcColumnName,
                        isChecked: true
                    })
                    response.data.tColumnList.push({
                        name: item.targetColumnName,
                        isChecked: true
                    })
                })
            }
            formData.data = response.data;
            formData.open = true;
        });
        } else if (type === 'view') {
        formData.title = '查看';
        selectById({syncTaskId:row.syncTaskId}).then(response => {
            if(response.data.dataSyncColumnDTOList?.length>0) {
                response.data.fColumnList = [];
                response.data.tColumnList = [];
                response.data.dataSyncColumnDTOList.forEach((item: any) => {
                    response.data.fColumnList.push({
                        name: item.srcColumnName,
                        isChecked: true
                    })
                    response.data.tColumnList.push({
                        name: item.targetColumnName,
                        isChecked: true
                    })
                })
            }
            formData.data = response.data;
            formData.open = true;
        });
    }
};

const confirm = () => {
    ElMessage.success("操作成功");
    getList();
}

const handleDelAction = (row: any) => {
    // console.log('handleDelAction', row);
    let ids = row ? row.syncTaskId : selectedRows.value.map(item => item.syncTaskId).join(',')

    if (!ids) {
        ElMessage.warning('请选择要删除的数据');
        return;
    }

    ElMessageBox.confirm('是否确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        deleteById({syncTaskId: ids}).then(() => {
            getList()
            ElMessage.success('删除成功')
        }).catch(function () {
        })
    }).catch(() => {
    })


};
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
